package com.zwp.base.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

private const val STARTING_PAGE_INDEX = 1

class BasePagingSource<V : Any>(val loadData:suspend (Int)->List<V>) : PagingSource<Int, V>() {

    var totalPage = 0

    override fun getRefreshKey(state: PagingState<Int, V>): Int? =
        null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, V> {
        val page =params.key ?: STARTING_PAGE_INDEX
        return try {
            loadData(page).let {
                LoadResult.Page(
                    data = it,
                    prevKey = if (page == STARTING_PAGE_INDEX) null else page - 1,
                    nextKey = if (page == totalPage) null else page + 1,
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
            LoadResult.Error(e)
        }
    }

}